package com.nuanshui.heatedloan.task.util;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.MethodInvoker;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.middleware.rabbitmq.RabbitmqMessageSender;
import com.nuanshui.heatedloan.task.annotation.Task;
import com.nuanshui.heatedloan.task.constant.TaskGlobalParams;
import com.nuanshui.heatedloan.task.facade.bean.JobParams;
import com.nuanshui.heatedloan.task.failover.TaskFailMessage;

/**
 * 定时 任务消息处理器
 * @param 
 * @author guohao
 * @date 2017年2月13日 上午10:02:05
 * @since $
 */
@Component("excutorTaskMsg")
public class ExcutorTaskMsg {
	
	@Autowired
	private RabbitmqMessageSender rabbitmqMessageSender;
	
	private Logger logger = LoggerFactory.getLogger(ExcutorTaskMsg.class);
	
	public  void onMessage(Message message, Channel channel,MethodInvoker methodInvoker,Task task) throws Exception {
		
		JobParams jobParams = null;
		String jobCode = null;
		try {
			String msg = new String(message.getBody());
			jobParams = new JobParams();
			if(StringUtils.isNotEmpty(msg)) {	
				 jobParams = JSON.parseObject(msg,JobParams.class);
			}
			jobCode = jobParams.getJobCode();
			if(StringUtils.isEmpty(jobCode)) {
				jobCode = CommonUtil.generateJobCode(jobParams);
			}
			MDC.put(TaskGlobalParams.JOB_LOG_CODE_KEY,jobCode);
			logger.info("--------------------------------接收到任务消息开始执行定时任务------------------------");
			methodInvoker.setArguments(new Object[]{jobParams});
			methodInvoker.prepare();
			methodInvoker.invoke();
			logger.info("---------------------------------定时任务执行完成---------------------------------");
		} catch (Exception e) {
			LogUtil.error(logger, "---------------------------定时任务执行失败-----------------------------",e);
			TaskFailMessage taskFailMessage = new TaskFailMessage();
			taskFailMessage.setFailReason(e);
			taskFailMessage.setJobParams(jobParams);
			taskFailMessage.setFailTime(new Date());
			taskFailMessage.setFailover(task.failover());
			taskFailMessage.setRetries(task.retries());
			taskFailMessage.setCode(jobCode);
			rabbitmqMessageSender.send(TaskGlobalParams.TASK_FAIL_MESSAGE_HANDLER, taskFailMessage,false);
		}finally{
			
			MDC.remove(TaskGlobalParams.JOB_LOG_CODE_KEY);
		}
	    channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
	}

}
